package com.aaa.spring.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

//标识这是个控制器 控制跳转的
@Controller
@RequestMapping("/file")
public class FileController {
    //跳转到文件上传页面
    @RequestMapping("/toFile")
    public ModelAndView toFile(){
        //ModelAndView 携带数据及视图信息
        ModelAndView mv = new ModelAndView();
        //设置视图
        mv.setViewName("file");
        return mv;
    }
    //文件上传
    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request, Model model) throws IOException {
        //获取指定目录的绝对路径
        String path = request.getSession().getServletContext().getRealPath("/static/");
        //获取待上传文件的原始的文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否存在
        File sourceFile = new File(path, fileName);
        //不存在，再上传
        if (!sourceFile.exists()) {
            //创建文件
            //目标文件对象
            File descFile = new File(path + File.separator + fileName);
            file.transferTo(descFile);
        }
        model.addAttribute("filename", file.getOriginalFilename());
        return "toDownload";
    }
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename, HttpServletRequest request)
            throws IOException {
        //应对：中文文件名乱码
        //filename.getBytes("iso-8859-1"):将原始的字符串以 西欧编码方式转换成字节数组
        //"utf-8" ： 重新以utf-8进行编码
        filename=new String(filename.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        //获取绝对路径
        String path=request.getSession().getServletContext().getRealPath("/static/");
        //待下载的文件对象
        File downloadFile=new File(path+"/"+filename);
        //头部信息对象
        HttpHeaders headers=new HttpHeaders();
        //响应类型：二进制数据流
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //浏览器如何接受数据
        headers.setContentDispositionFormData("attachment", filename);
        //FileUtils.readFileToByteArray(downloadFile):  将文件对象转换成字节数组
        return new ResponseEntity<>(FileUtils.readFileToByteArray(downloadFile),
                headers, HttpStatus.CREATED);
    }



}
